import React, { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import {
  StyleSheet,
  FlatList,
  Platform,
  PermissionsAndroid,
  AppState,
  InteractionManager,
  StatusBar,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import SafeTabBarWrapper from '../components/SafeTabBarWrapper';
import HomeHeader from '../components/HomeHeader';
import HomeContent from '../components/HomeContent';
import HomeModals from '../components/HomeModals';
import AutoVoiceGuide from '../components/AutoVoiceGuide';
import voiceService from '../services/voiceService';
import { fetchFoodCulture } from '../api/foodCulture';
import { locationAPI } from '../api';
import { getCityMapRegion } from '../utils/cityRegions';
import { fetchWeatherByCity } from '../utils/weatherUtils';
import {
  getCurrentPosition,
  getLocationInfo,
  getCityStatistics,
  convertWgs84ToGcj02ViaAmap,
  wgs84ToGcj02,
} from '../utils/locationUtils';
import Compass from '../modules/CompassModule';
import {
  checkPermission,
  requestPermission
} from '../utils/permissionsUtils';
import { getAmapIPLocation } from '../utils/amapLocation';
import { DEFAULT_LOCATION, COLORS } from '../styles/constants';
import { FullHomeSkeletonLoader } from '../components/SkeletonLoader';

export default function HomeScreen() {
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();
  const [city, setCity] = useState('定位中...');
  const [cityList, setCityList] = useState([]); // 城市列表
  const [pickerVisible, setPickerVisible] = useState(false);

  const [_locationStatus, setLocationStatus] = useState('idle'); // idle, locating, success, failed
  const [weather, setWeather] = useState(null);
  const [isInitialLoading, setIsInitialLoading] = useState(true); // 首次加载状态
  const [foodCulture, setFoodCulture] = useState([]);
  const [foodCultureLoading, setFoodCultureLoading] = useState(false);
  const [mapRegion, setMapRegion] = useState(DEFAULT_LOCATION.urumqi);
  // 新增：保存 adcode（目前仅控制台打印，保留以便后续使用）
  const [_adcode, setAdcode] = useState(null);
  // 新增：保存城市景区数量（来自 count 接口）
  const [scenicAreasCount, setScenicAreasCount] = useState(0);
  // 新增：保存API返回的景区数据
  const [apiScenicAreas, setApiScenicAreas] = useState([]);
  // 新增：保存景区数据（大图标+小图标）
  const [scenicAreasWithSpots, setScenicAreasWithSpots] = useState([]);
  const [scenicAreasLoading, setScenicAreasLoading] = useState(false);
  // 新增：保存地图专用景区数据
  const [mapScenicAreas, setMapScenicAreas] = useState([]);
  const [mapScenicAreasLoading, setMapScenicAreasLoading] = useState(false);
  // 新增：保存周边景区数据
  const [otherScenicAreas, setOtherScenicAreas] = useState([]);
  const [otherScenicLoading, setOtherScenicLoading] = useState(false);
  // 新增：保存省内旅游路线数据
  const [provinceTours, setProvinceTours] = useState([]);
  const [provinceToursLoading, setProvinceToursLoading] = useState(false);
  // 新增：保存跨省旅游路线数据
  const [crossProvinceTours, setCrossProvinceTours] = useState([]);
  const [crossProvinceToursLoading, setCrossProvinceToursLoading] =
    useState(false);
  // 新增：保存用户当前位置
  const [currentLocation, setCurrentLocation] = useState(null);
  // 新增：保存用户当前方向（罗盘角度）
  const [heading, setHeading] = useState(0);
  const lastHeadingUpdateTime = useRef(0);
  // 自动语音导览状态
  const [showAutoVoiceGuide, setShowAutoVoiceGuide] = useState(false);
  const [hasLocationPermission, setHasLocationPermission] = useState(false);
  const [shouldAutoStartVoice, setShouldAutoStartVoice] = useState(false);
  const [hasAutoStarted, setHasAutoStarted] = useState(false);
  // WebAmap 已内聚内部状态
  const autoGuideTimerRef = React.useRef(null);
  const headingWatchId = React.useRef(null);

  const clearAutoGuideTimer = React.useCallback(() => {
    if (autoGuideTimerRef.current) {
      clearTimeout(autoGuideTimerRef.current);
      autoGuideTimerRef.current = null;
    }
  }, []);

  // 启动实时罗盘监听（使用原生罗盘传感器，静止时也有效）
  const startHeadingWatch = useCallback(async () => {
    try {
      // 检查罗盘是否可用
      const isAvailable = await Compass.isAvailable();
      if (!isAvailable) {
        console.warn('[罗盘] 设备不支持罗盘');
        return;
      }

      // 开始监听罗盘方向（添加节流，避免过于频繁更新）
      const subscription = Compass.startHeadingUpdates((data) => {
        const { heading: newHeading } = data;
        if (typeof newHeading === 'number' && newHeading >= 0) {
          const now = Date.now();
          // 节流：每500ms最多更新一次
          if (now - lastHeadingUpdateTime.current > 500) {
            setHeading(Math.round(newHeading));
            lastHeadingUpdateTime.current = now;
          }
        }
      });

      headingWatchId.current = subscription;
    } catch (error) {
      console.error('[罗盘] 启动失败:', error);
    }
  }, []);

  // 停止实时罗盘监听
  const stopHeadingWatch = useCallback(() => {
    if (headingWatchId.current !== null) {
      try {
        Compass.stopHeadingUpdates(headingWatchId.current);
        headingWatchId.current = null;
      } catch (error) {
        console.error('[罗盘] 停止失败:', error);
      }
    }
  }, []);

  // 获取城市列表
  const fetchCityList = useCallback(async () => {
    try {
      const response = await locationAPI.getCityList();

      // 尝试多种可能的数据路径
      let citiesData = response?.data?.data || response?.data || response;

      // 检查数据格式：可能是数组或按字母分组的对象
      let cities = [];

      if (Array.isArray(citiesData)) {
        // 如果是数组，直接使用
        cities = citiesData;
      } else if (typeof citiesData === 'object' && citiesData !== null) {
        // 如果是对象（按字母分组），将所有分组的城市合并成一个数组
        const allGroups = Object.values(citiesData);
        cities = allGroups.flat();
      } else {
      }


      if (cities.length > 0) {
      }

      setCityList(cities);
    } catch (error) {
      console.error('[HomeScreen] 获取城市列表失败:', error.message || error);
      // 使用空数组，让 CityPickerModal 使用默认城市列表
      setCityList([]);
    }
  }, []);

  // 初始化位置服务和权限（优化版：城市列表异步加载）
  useEffect(() => {
    // 异步加载城市列表，不阻塞定位
    fetchCityList().catch(error => {
      console.warn('[城市列表] 加载失败:', error);
    });

    // 立即初始化定位（不等待城市列表）
    initializeLocation()
      .then(() => {
        setShouldAutoStartVoice(true);
      })
      .catch(error => {
        console.warn('[定位] 初始化失败:', error);
      });

    // 启动实时方向监听（罗盘）
    startHeadingWatch();

    // 清理函数
    return () => {
      stopHeadingWatch();
    };
  }, []);

  // 监听应用状态变化，事件驱动检查权限状态（优化：移除频繁的setInterval）
  useEffect(() => {
    let isMounted = true;

    // 检查权限并更新状态
    const checkAndUpdatePermission = async () => {
      if (!isMounted) return;

      const hasLocation = await checkPermission('location');

      // 使用函数式更新确保获取最新状态
      setHasLocationPermission(prevHasLocation => {
        if (hasLocation !== prevHasLocation) {
          const wasDenied = !prevHasLocation;
          const isNowGranted = hasLocation;

          // 🚀 关键修复：当权限从无到有时，立即触发定位和数据加载
          if (wasDenied && isNowGranted) {
            // 延迟一小段时间确保状态更新完成
            setTimeout(() => {
              if (isMounted) {
                tryGetLocation().then(() => {
                  if (isMounted) {
                    setShouldAutoStartVoice(true);
                  }
                });
              }
            }, 100);
          }

          return hasLocation;
        }
        return prevHasLocation;
      });
    };

    // 立即检查一次（权限可能刚授予）
    checkAndUpdatePermission();

    // 监听应用状态变化，只在应用从后台回到前台时检查权限
    const subscription = AppState.addEventListener('change', nextAppState => {
      if (nextAppState === 'active') {
        // 应用回到前台时检查权限
        checkAndUpdatePermission();
      }
    });

    return () => {
      isMounted = false;
      subscription?.remove();
    };
  }, [tryGetLocation]);

  // 监听城市和数据加载状态，判断是否完成初始加载（优化版：移除人为延迟）
  useEffect(() => {
    // 只有当城市定位完成且至少有一个数据源有数据时，立即结束骨架屏
    if (
      city !== '定位中...' &&
      (scenicAreasWithSpots.length > 0 ||
        otherScenicAreas.length > 0 ||
        foodCulture.length > 0 ||
        apiScenicAreas.length > 0)
    ) {
      // 立即隐藏骨架屏，不再人为延长
      setIsInitialLoading(false);
    }
  }, [
    city,
    scenicAreasWithSpots,
    otherScenicAreas,
    foodCulture,
    apiScenicAreas,
  ]);

  // 初始化位置（优化版：移除不必要的延迟）
  const initializeLocation = async () => {
    try {
      // 直接检查权限，不再延迟
      const hasLocation = await checkPermission('location');


      if (hasLocation) {
        setHasLocationPermission(true);
        await tryGetLocation();
        setShouldAutoStartVoice(true);
      } else {
        setHasLocationPermission(false);
        // 使用乌鲁木齐的经纬度作为默认位置
        const { latitude: urumqiLatitude, longitude: urumqiLongitude } =
          DEFAULT_LOCATION.urumqi;

        try {
          const locationInfo = await getLocationInfo(
            urumqiLongitude,
            urumqiLatitude,
          );
          const { city: apiCity, adcode: apiAdcode } = locationInfo;

          // 设置当前位置为默认位置
          setCurrentLocation({
            latitude: urumqiLatitude,
            longitude: urumqiLongitude,
          });

          // 立即更新城市信息
          if (apiCity) {
            setCity(apiCity);
            const region = getCityMapRegion(apiCity);
            setMapRegion(region);
          } else {
            setCity('乌鲁木齐');
            setMapRegion({
              latitude: urumqiLatitude,
              longitude: urumqiLongitude,
              latitudeDelta: 0.02,
              longitudeDelta: 0.02,
            });
          }

          if (apiAdcode) {
            setAdcode(apiAdcode);
            loadAllCityData(apiAdcode, urumqiLatitude, urumqiLongitude);
          }
          setShouldAutoStartVoice(true);
        } catch {
          // 如果API调用失败，直接设置为乌鲁木齐
          setCity('乌鲁木齐');
          setCurrentLocation({
            latitude: urumqiLatitude,
            longitude: urumqiLongitude,
          });
          setMapRegion({
            latitude: urumqiLatitude,
            longitude: urumqiLongitude,
            latitudeDelta: 0.02,
            longitudeDelta: 0.02,
          });
          setShouldAutoStartVoice(true);
        }
      }
    } catch {
      // 使用乌鲁木齐的经纬度作为默认位置
      const { latitude: urumqiLatitude, longitude: urumqiLongitude } =
        DEFAULT_LOCATION.urumqi;

      try {
        const locationInfo = await getLocationInfo(
          urumqiLongitude,
          urumqiLatitude,
        );
        const { city: apiCity, adcode: apiAdcode } = locationInfo;

        // 立即更新城市信息
        if (apiCity) {
          setCity(apiCity);
          const region = getCityMapRegion(apiCity);
          setMapRegion(region);
        } else {
          setCity('乌鲁木齐');
          setMapRegion({
            latitude: urumqiLatitude,
            longitude: urumqiLongitude,
            latitudeDelta: 0.02,
            longitudeDelta: 0.02,
          });
        }

        // 设置当前位置为默认位置
        setCurrentLocation({
          latitude: urumqiLatitude,
          longitude: urumqiLongitude,
        });

        // 🚀 立即发起所有数据加载（不等待）
        if (apiAdcode) {
          setAdcode(apiAdcode);
          loadAllCityData(apiAdcode, urumqiLatitude, urumqiLongitude);
        }
        setShouldAutoStartVoice(true);
      } catch {
        // 如果API调用失败，直接设置为乌鲁木齐
        setCity('乌鲁木齐');
        setCurrentLocation({
          latitude: urumqiLatitude,
          longitude: urumqiLongitude,
        });
        setMapRegion({
          latitude: urumqiLatitude,
          longitude: urumqiLongitude,
          latitudeDelta: 0.02,
          longitudeDelta: 0.02,
        });
        setShouldAutoStartVoice(true);
      }
    }
  };

  // 尝试获取位置（优化版：只使用高德定位和IP定位）
  const tryGetLocation = useCallback(async () => {
    setLocationStatus('locating');
    setCity('定位中...');

    // 策略1：使用高德原生定位（GCJ-02坐标，5秒超时）
    try {
      const position = await getCurrentPosition({
        timeout: 5000, // 5秒超时，更快响应
      });

      const latitude = position?.coords?.latitude;
      const longitude = position?.coords?.longitude;

      // 验证坐标有效性
      if (typeof latitude === 'number' && typeof longitude === 'number') {

        // 高德定位成功，坐标已经是 GCJ-02，不需要任何转换
        setCurrentLocation({ latitude, longitude });

        // 优先使用高德返回的城市信息（最可靠）
        const amapCity = position.amap?.city;

        if (amapCity) {
          // 高德直接返回了城市信息，立即使用
          setCity(amapCity);
          setMapRegion(getCityMapRegion(amapCity));

          // 异步获取adcode和加载数据，不阻塞UI
          (async () => {
            try {
              const locationInfo = await getLocationInfo(longitude, latitude);
              const { adcode: apiAdcode } = locationInfo;
              if (apiAdcode) {
                setAdcode(apiAdcode);
                loadAllCityData(apiAdcode, latitude, longitude);
              } else {
                loadAllCityData(null, latitude, longitude);
              }
            } catch {
              // 即使后端API失败，也已经有城市信息了
              loadAllCityData(null, latitude, longitude);
            }
          })();
        } else {
          // 高德没返回城市信息，调用后端API
          try {
            const locationInfo = await getLocationInfo(longitude, latitude);
            const { city: apiCity, adcode: apiAdcode } = locationInfo;

            if (apiCity) {
              setCity(apiCity);
              setMapRegion(getCityMapRegion(apiCity));
            } else {
              setCity('定位结果');
              setMapRegion(prev => ({
                ...prev,
                latitude,
                longitude,
              }));
            }

            if (apiAdcode) {
              setAdcode(apiAdcode);
              loadAllCityData(apiAdcode, latitude, longitude);
            } else {
              loadAllCityData(null, latitude, longitude);
            }
          } catch {
            // API失败，使用默认显示
            setCity('定位结果');
            setMapRegion(prev => ({
              ...prev,
              latitude,
              longitude,
            }));
            loadAllCityData(null, latitude, longitude);
          }
        }

        setLocationStatus('success');
        return;
      }
    } catch (error) {
    }

    // 策略2：降级使用高德IP定位
    try {
      const amapLocation = await getAmapIPLocation();
      setLocationStatus('success');

      if (amapLocation.city && amapLocation.adcode) {
        setCity(amapLocation.city);
        setAdcode(amapLocation.adcode);
        setMapRegion(getCityMapRegion(amapLocation.city));
        setCurrentLocation({
          latitude: amapLocation.latitude,
          longitude: amapLocation.longitude,
        });
        loadAllCityData(
          amapLocation.adcode,
          amapLocation.latitude,
          amapLocation.longitude,
        );
        return;
      }

      setCurrentLocation({
        latitude: amapLocation.latitude,
        longitude: amapLocation.longitude,
      });
      setCity(amapLocation.city || '定位结果');
      if (amapLocation.city) {
        setMapRegion(getCityMapRegion(amapLocation.city));
      }
      if (amapLocation.adcode) {
        setAdcode(amapLocation.adcode);
        loadAllCityData(
          amapLocation.adcode,
          amapLocation.latitude,
          amapLocation.longitude,
        );
      }
      return;
    } catch {
      // 高德 IP 定位失败
    }

    // 策略3：所有定位方式都失败，使用乌鲁木齐国际大巴扎作为默认位置
    try {
      // 乌鲁木齐国际大巴扎的坐标（GCJ-02）
      const { latitude: defaultLatitude, longitude: defaultLongitude } =
        DEFAULT_LOCATION.urumqi;

      setCurrentLocation({
        latitude: defaultLatitude,
        longitude: defaultLongitude,
      });

      const locationInfo = await getLocationInfo(
        defaultLongitude,
        defaultLatitude,
      );
      const { city: apiCity, adcode: apiAdcode } = locationInfo;

      if (apiCity) {
        setCity(apiCity);
        setMapRegion(getCityMapRegion(apiCity));
      } else {
        setCity('乌鲁木齐市');
        setMapRegion({
          latitude: defaultLatitude,
          longitude: defaultLongitude,
          latitudeDelta: 0.02,
          longitudeDelta: 0.02,
        });
      }

      if (apiAdcode) {
        setAdcode(apiAdcode);
        loadAllCityData(apiAdcode, defaultLatitude, defaultLongitude);
      } else {
        loadAllCityData(null, defaultLatitude, defaultLongitude);
      }

      setLocationStatus('success');
      // 确保语音播报能够启动
      setShouldAutoStartVoice(true);
      return;
    } catch {
      // 如果连默认位置都失败了，至少设置基本信息
      setCity('乌鲁木齐市');
      setMapRegion(DEFAULT_LOCATION.urumqi);
      setLocationStatus('failed');
    }
  }, []);

  // 获取景区数据（大图标+小图标）
  const fetchScenicAreasWithSpots = async (cityCode, latitude, longitude) => {
    try {
      setScenicAreasLoading(true);

      const params = {};

      // 默认携带城市代码，同时尽可能附带经纬度，方便后端根据需要选择
      if (cityCode) {
        params.cityCode = cityCode;
      }
      if (latitude && longitude) {
        params.latitude = latitude.toString();
        params.longitude = longitude.toString();
      }

      const response = await locationAPI.getCityScenicAreasWithSpots(params);

      const payload = response?.data?.data || response?.data || null;

      if (!payload) {
        setScenicAreasWithSpots([]);
      } else {
        // 主景区（大图标）- 标记为景区类型
        const mainArea = {
          id: payload.id,
          areaName: payload.areaName || payload.name,
          name: payload.areaName || payload.name,
          coverImage: payload.coverImage || payload.image,
          image: payload.coverImage || payload.image,
          address: payload.address || '',
          latitude: payload.latitude ? parseFloat(payload.latitude) : null,
          longitude: payload.longitude ? parseFloat(payload.longitude) : null,
          rating: payload.rating || '4.7',
          distance: payload.distanceKm ? `${payload.distanceKm}km` : null,
          level: payload.level,
          type: 'scenicArea', // 标记为景区
          raw: payload,
        };

        // 景点列表（小图标）- 标记为景点类型
        const spots = Array.isArray(payload.scenicSpots)
          ? payload.scenicSpots.map((s, i) => ({
            id: s.id || `spot_${i}`,
            areaName: s.name,
            name: s.name,
            coverImage: s.image,
            image: s.image,
            address: s.address || '',
            latitude: s.latitude ? parseFloat(s.latitude) : null,
            longitude: s.longitude ? parseFloat(s.longitude) : null,
            rating: '4.6',
            distance: s.distanceKm ? `${s.distanceKm}km` : null,
            level: s.level,
            type: 'scenicSpot', // 标记为景点
            parentAreaId: payload.id, // 关联父景区ID
            parentAreaName: payload.areaName || payload.name, // 关联父景区名称
            raw: s,
          }))
          : [];

        const list = [mainArea, ...spots].filter(
          it =>
            it.latitude &&
            it.longitude &&
            !isNaN(it.latitude) &&
            !isNaN(it.longitude),
        );
        setScenicAreasWithSpots(list);
      }
    } catch (error) {
      setScenicAreasWithSpots([]);
    } finally {
      setScenicAreasLoading(false);
    }
  };

  const fetchMapScenicAreas = async cityCode => {
    try {
      setMapScenicAreasLoading(true);

      if (!cityCode) {
        setMapScenicAreas([]);
        return;
      }

      const response = await locationAPI.getMapScenicAreas(cityCode);

      let dataList = [];

      if (response?.data?.data?.scenicAreasList) {
        dataList = response.data.data.scenicAreasList;
      } else if (Array.isArray(response?.data?.data)) {
        dataList = response.data.data;
      } else if (Array.isArray(response?.data)) {
        dataList = response.data;
      } else if (Array.isArray(response)) {
        dataList = response;
      }

      if (Array.isArray(dataList) && dataList.length > 0) {
        const mapData = dataList
          .map((item, index) => ({
            id: item.id || `map_${index}`,
            name: item.areaName || item.name || '未知景区',
            areaName: item.areaName || item.name,
            coverImage: item.coverImage || item.image,
            image: item.coverImage || item.image,
            address: item.address || '',
            latitude: item.latitude ? parseFloat(item.latitude) : null,
            longitude: item.longitude ? parseFloat(item.longitude) : null,
            rating: item.rating || '4.5',
            distance: item.distanceKm ? `${item.distanceKm}km` : null,
            level: item.level,
            type: 'scenicArea',
            raw: item,
          }))
          .filter(
            it =>
              it.latitude &&
              it.longitude &&
              !Number.isNaN(it.latitude) &&
              !Number.isNaN(it.longitude),
          );

        setMapScenicAreas(mapData);
      } else {
        setMapScenicAreas([]);
      }
    } catch {
      setMapScenicAreas([]);
    } finally {
      setMapScenicAreasLoading(false);
    }
  };

  // 获取周边景区数据
  const fetchOtherScenicAreas = async (cityCode, latitude, longitude) => {
    try {
      setOtherScenicLoading(true);

      const params = {};

      if (cityCode) {
        params.cityCode = cityCode;
      }
      if (latitude && longitude) {
        params.latitude = latitude.toString();
        params.longitude = longitude.toString();
      }
      params.pageNum = '1';
      params.pageSize = '10';

      const response = await locationAPI.getOtherScenicAreas(params);

      const otherAreas =
        response?.data?.data?.rows ||
        response?.data?.rows ||
        response?.data?.data ||
        response?.data ||
        [];

      setOtherScenicAreas(otherAreas);
    } catch {
      setOtherScenicAreas([]);
    } finally {
      setOtherScenicLoading(false);
    }
  };

  // 获取省内旅游路线数据
  const fetchProvinceTours = async cityCode => {
    try {
      setProvinceToursLoading(true);

      const params = {};

      if (cityCode) {
        params.cityCode = cityCode;
      }
      params.pageNum = '1';
      params.pageSize = '10';

      const response = await locationAPI.getProvinceTours(params);

      const tours =
        response?.data?.data?.rows ||
        response?.data?.rows ||
        response?.data?.data ||
        response?.data ||
        [];

      setProvinceTours(tours);
    } catch {
      setProvinceTours([]);
    } finally {
      setProvinceToursLoading(false);
    }
  };

  // 获取跨省旅游路线数据
  const fetchCrossProvinceTours = async () => {
    try {
      setCrossProvinceToursLoading(true);

      const params = {
        pageNum: '1',
        pageSize: '10',
      };

      const response = await locationAPI.getCrossProvinceTours(params);

      const tours =
        response?.data?.data?.rows ||
        response?.data?.rows ||
        response?.data?.data ||
        response?.data ||
        [];

      setCrossProvinceTours(tours);
    } catch {
      setCrossProvinceTours([]);
    } finally {
      setCrossProvinceToursLoading(false);
    }
  };

  // 获取美食与文创数据
  const fetchFoodCultureData = async cityCode => {
    try {
      setFoodCultureLoading(true);

      const fc = await fetchFoodCulture(cityCode);

      setFoodCulture(fc);
    } catch {
      setFoodCulture([]);
    } finally {
      setFoodCultureLoading(false);
    }
  };

  // 统一的数据加载函数（优化版：减少延迟，分级加载）
  const loadAllCityData = (apiAdcode, latitude, longitude) => {
    // 立即设置 loading 状态
    setScenicAreasLoading(true);
    setOtherScenicLoading(true);
    setProvinceToursLoading(true);
    setCrossProvinceToursLoading(true);
    setFoodCultureLoading(true);

    // 优先级1：关键数据立即加载（景区数据）
    (async () => {
      try {
        await fetchScenicAreasWithSpots(apiAdcode, latitude, longitude);
      } catch { }
    })();

    (async () => {
      try {
        const stats = await getCityStatistics(apiAdcode);
        setScenicAreasCount(stats.scenicAreasCount);
        setApiScenicAreas(stats.scenicAreasList);
      } catch { }
    })();

    // 优先级2：次要数据延迟加载（减少延迟时间）
    const interaction = InteractionManager.runAfterInteractions(() => {

      // 地图景区数据
      (async () => {
        try {
          await fetchMapScenicAreas(apiAdcode);
        } catch { }
      })();

      // 周边景区数据
      (async () => {
        try {
          await fetchOtherScenicAreas(apiAdcode, latitude, longitude);
        } catch { }
      })();

      // 美食数据
      (async () => {
        try {
          await fetchFoodCultureData(apiAdcode);
        } catch { }
      })();
    });

    // 优先级3：非关键数据更晚加载（旅游路线）
    setTimeout(() => {
      (async () => {
        try {
          await fetchProvinceTours(apiAdcode);
        } catch { }
      })();

      (async () => {
        try {
          await fetchCrossProvinceTours();
        } catch { }
      })();
    }, 1000); // 1秒后加载旅游路线

    return () => {
      interaction.cancel();
    };
  };

  // 获取天气数据 - 增强错误处理和重试逻辑
  useEffect(() => {
    let isMounted = true;
    let retryCount = 0;
    const maxRetries = 2;

    const fetchWeather = async () => {
      // 城市信息必须有效才获取天气
      if (!city || city === '定位中...' || city === '定位失败') {
        return;
      }

      try {
        const w = await fetchWeatherByCity(city, _adcode);

        if (isMounted) {
          if (w) {
            setWeather(w);
          } else {
            // 天气数据为空时，如果还有重试次数，则重试
            if (retryCount < maxRetries) {
              retryCount++;
              setTimeout(() => {
                if (isMounted) {
                  fetchWeather();
                }
              }, 1000 * retryCount); // 递增延迟：1s, 2s
            }
          }
        }
      } catch (error) {
        console.error('[HomeScreen] 获取天气数据失败:', error);
        // 失败时也尝试重试
        if (isMounted && retryCount < maxRetries) {
          retryCount++;
          setTimeout(() => {
            if (isMounted) {
              fetchWeather();
            }
          }, 1000 * retryCount);
        }
      }

      // 更新地图区域
      if (isMounted) {
        const newRegion = getCityMapRegion(city);
        setMapRegion(newRegion);
      }
    };

    // iOS需要稍微延迟一下，确保其他状态更新完成
    const delay = Platform.OS === 'ios' ? 200 : 0;
    const timer = setTimeout(() => {
      fetchWeather();
    }, delay);

    return () => {
      isMounted = false;
      clearTimeout(timer);
    };
  }, [city, _adcode]);

  // 🎤 监听景区数据加载完成，自动开启语音导览
  // 优化：添加权限检查，确保权限弹窗优先显示，避免Modal冲突
  useEffect(() => {
    // 条件：有景区数据（来自getNearestScenicAreaWithSpots接口）、还没自动开启过、城市已定位
    // 优化：延迟显示，确保获取到最终的景区数据
    if (
      scenicAreasWithSpots.length > 0 &&
      !hasAutoStarted &&
      shouldAutoStartVoice &&
      city !== '定位中...' &&
      city !== '定位失败'
    ) {
      // 检查权限状态，确保权限弹窗优先显示
      // iOS需要更长的延迟时间以确保UI完全准备好
      const checkAndShowVoiceGuide = async () => {
        // iOS需要更长的延迟，给权限弹窗足够时间显示
        const permissionCheckDelay = Platform.OS === 'ios' ? 800 : 500;
        await new Promise(resolve => setTimeout(resolve, permissionCheckDelay));

        // 再次检查权限状态，如果权限已授予才显示语音导览弹窗
        const hasLocation = await checkPermission('location');
        const hasMicrophone = await checkPermission('microphone');

        // 只有权限都已授予时才显示语音导览弹窗，避免与权限弹窗冲突
        if (hasLocation && hasMicrophone) {
          clearAutoGuideTimer();
          // iOS需要更长的延迟以确保弹窗可以正常显示和响应
          // 增加延迟时间，确保获取到最终的景区数据
          const showDelay = Platform.OS === 'ios' ? 500 : 300;
          autoGuideTimerRef.current = setTimeout(() => {
            setShowAutoVoiceGuide(true);
            setHasAutoStarted(true);
          }, showDelay);
        } else {
          // 权限未授予，延迟再次尝试（等待用户处理权限弹窗）
          clearAutoGuideTimer();
          const retryDelay = Platform.OS === 'ios' ? 3000 : 2000;
          autoGuideTimerRef.current = setTimeout(() => {
            checkAndShowVoiceGuide();
          }, retryDelay);
        }
      };

      clearAutoGuideTimer();
      // 增加初始延迟，确保获取到最终的景区数据（而不是中间状态）
      // 这样可以避免显示"红光山大佛寺"后又改为"白鸟湖湿地"的问题
      const initialDelay = Platform.OS === 'ios' ? 2000 : 1500;
      autoGuideTimerRef.current = setTimeout(() => {
        checkAndShowVoiceGuide();
      }, initialDelay);

      return () => clearAutoGuideTimer();
    }
  }, [scenicAreasWithSpots, hasAutoStarted, shouldAutoStartVoice, city, hasLocationPermission]);

  const handleMarkerPress = useCallback(
    attraction => {
      const itemData = attraction.raw || attraction;
      const areaType = itemData.areaType || 1; // 默认为景区
      navigation.navigate('AttractionDetail', {
        attraction: itemData,
        itemType: areaType === 1 ? 'scenicArea' : 'scenicSpot',
        itemId: itemData.id || itemData.scenicAreaId,
        areaType: areaType,
      });
    },
    [navigation],
  );

  const handleMasonryItemPress = useCallback(
    item => {
      const itemData = item.raw || item;
      const areaType =
        itemData.raw?.areaType || itemData.areaType || item.areaType;

      navigation.navigate('AttractionDetail', {
        attraction: itemData.raw || itemData,
        itemType: areaType === 1 ? 'scenicArea' : 'scenicSpot',
        itemId: itemData.id,
        areaType: areaType,
      });
    },
    [navigation],
  );

  const handleHorizontalItemPress = useCallback(
    it => {
      const itemData = it.raw || it;
      const areaType =
        itemData.raw?.areaType || itemData.areaType || it.areaType;

      navigation.navigate('AttractionDetail', {
        attraction: itemData.raw || itemData,
        itemType: areaType === 1 ? 'scenicArea' : 'scenicSpot',
        itemId: itemData.id,
        areaType: areaType,
      });
    },
    [navigation],
  );

  const handleSearchPress = useCallback(() => {
    navigation.navigate('Search', { city });
  }, [navigation, city]);

  // 处理地图图标点击
  const handleMapPress = useCallback(() => {
    navigation.navigate('Map', {
      city,
      region: mapRegion,
      attractions: mapScenicAreas,
      currentLocation,
    });
  }, [navigation, city, mapRegion, mapScenicAreas, currentLocation]);

  // 处理城市选择
  const handleCitySelect = useCallback(async selectedCityData => {
    setPickerVisible(false);

    // 处理城市数据：可能是字符串（城市名）或对象（包含cityName和code/adcode）
    const cityName =
      typeof selectedCityData === 'string'
        ? selectedCityData
        : selectedCityData?.cityName || selectedCityData?.name;
    // ⚠️ 注意：后端返回的字段是 code，不是 adcode
    const cityAdcode =
      typeof selectedCityData === 'object'
        ? selectedCityData?.code ||
        selectedCityData?.adcode ||
        selectedCityData?.cityCode
        : null;

    // 更新城市名称
    setCity(cityName);

    // 更新地图区域（获取城市中心点坐标）
    const newRegion = getCityMapRegion(cityName);
    setMapRegion(newRegion);

    // 更新 adcode
    if (cityAdcode) {
      setAdcode(cityAdcode);
    }

    // 使用城市中心点坐标重新加载数据
    // 这样地图、景区、美食等都会显示新城市的数据
    const cityLatitude = newRegion.latitude;
    const cityLongitude = newRegion.longitude;

    // 重新加载该城市的所有数据（使用城市中心点坐标）
    loadAllCityData(cityAdcode, cityLatitude, cityLongitude);

    // 获取天气信息
    const w = await fetchWeatherByCity(cityName, cityAdcode);
    setWeather(w);
  }, []);

  // 处理位置栏点击
  const handleLocationPress = useCallback(async () => {
    // 如果城市列表还没加载，先加载
    if (!cityList || cityList.length === 0) {
      await fetchCityList();
    }

    setPickerVisible(true);
  }, [cityList, fetchCityList]);

  // 处理地图定位按钮点击（重新定位）
  const handleRequestLocation = useCallback(async () => {
    // 先检查是否已有权限
    let hasLocation = await checkPermission('location');

    if (!hasLocation) {
      // 没有权限，主动请求
      hasLocation = await requestPermission('location');
    }

    if (hasLocation) {
      // 有权限或刚刚授予权限，立即更新状态并定位
      setHasLocationPermission(true);
      await tryGetLocation();
      setShouldAutoStartVoice(true);
      return true;
    } else {
      // 用户拒绝授权
      setHasLocationPermission(false);
      return false;
    }
  }, [tryGetLocation]);

  const handleMapLocationPress = useCallback(async () => {
    if (!hasLocationPermission) {
      // 请求权限并定位
      const granted = await handleRequestLocation();
      // 权限授予后，横幅会自动消失（因为 hasLocationPermission 变为 true）
      // 定位成功后地图会自动更新
      return;
    }
    // 已有权限，重新定位
    await tryGetLocation();
  }, [hasLocationPermission, handleRequestLocation, tryGetLocation]);

  // 处理美食更多按钮点击
  const handleFoodMorePress = useCallback(() => {
    navigation.navigate('FoodCultureList', {
      city: _adcode || city, // 传递城市代码，如果没有则传城市名
      cityName: city, // 同时传递城市名称用于显示
    });
  }, [navigation, city, _adcode]);

  // 处理美食项目点击
  const handleFoodItemPress = useCallback(
    item => {
      navigation.navigate('FoodCultureDetail', {
        item: item, // 传递完整的美食文创数据
      });
    },
    [navigation],
  );

  // 处理当前景区数量点击
  const handleCurrentScenicPress = useCallback(() => {
    navigation.navigate('ScenicAreaList', {
      city: city,
      cityCode: _adcode,
      scenicAreasData: scenicAreasWithSpots, // 传递当前景区数据
      isCurrentScenic: true, // 标记为当前景区
    });
  }, [navigation, city, _adcode, scenicAreasWithSpots]);

  // 将API返回的景区数据转换为地图组件需要的格式 - 使用 useMemo 优化性能
  const convertedApiAttractions = useMemo(() => {
    if (apiScenicAreas.length === 0) return [];

    return apiScenicAreas
      .map((area, index) => ({
        id: area.id || `api_${index}`,
        name: area.areaName || area.name || '未知景区',
        image:
          area.coverImage ||
          'https://via.placeholder.com/300x200?text=景区图片',
        address: area.address || '',
        latitude: area.latitude ? parseFloat(area.latitude) : null,
        longitude: area.longitude ? parseFloat(area.longitude) : null,
        rating: area.rating || '4.0',
        level: area.level || '',
        province: area.province || '',
        city: area.city || '',
        distance: area.distanceKm ? `${area.distanceKm}km` : null,
        raw: area, // 保存原始数据
      }))
      .filter(
        attraction =>
          attraction.latitude &&
          attraction.longitude &&
          !isNaN(attraction.latitude) &&
          !isNaN(attraction.longitude),
      );
  }, [apiScenicAreas]);

  // 获取当前显示的景点数据 - 使用 useMemo 优化性能
  const currentAttractions = useMemo(() => {
    // 若新接口有数据，优先使用
    if (scenicAreasWithSpots.length > 0) return scenicAreasWithSpots;
    // 其次使用API聚合的景区数据
    if (apiScenicAreas.length > 0) return convertedApiAttractions;
    // 没有数据时返回空数组
    return [];
  }, [scenicAreasWithSpots, apiScenicAreas.length, convertedApiAttractions]);

  // 计算当前景区数量（只计算主景区，不包括景点）
  const currentScenicAreasCount = useMemo(() => {
    // 只计算 type === 'scenicArea' 的项（主景区/大图标）
    return scenicAreasWithSpots.filter(item => item.type === 'scenicArea').length;
  }, [scenicAreasWithSpots]);

  // 创建列表数据 - 使用 useMemo 优化性能
  const listData = useMemo(() => {
    const data = [];

    // 头部区域
    data.push({ type: 'header', id: 'header' });

    // 内容区域
    data.push({ type: 'content', id: 'content' });

    return data;
  }, []);

  // 渲染列表项 - 使用 useCallback 优化性能
  const renderItem = useCallback(
    ({ item }) => {
      switch (item.type) {
        case 'header':
          return (
            <HomeHeader
              city={city}
              weather={weather}
              scenicAreasCount={scenicAreasCount}
              attractionCount={0}
              onLocationPress={handleLocationPress}
              onSearchPress={handleSearchPress}
              onMapPress={handleMapPress}
            />
          );

        case 'content':
          return (
            <HomeContent
              city={city}
              currentAttractions={currentAttractions}
              foodCulture={foodCulture}
              foodCultureLoading={foodCultureLoading}
              provinceRecs={[]}
              provinceTours={provinceTours}
              provinceToursLoading={provinceToursLoading}
              crossProvinceRoutes={[]}
              crossProvinceTours={crossProvinceTours}
              crossProvinceToursLoading={crossProvinceToursLoading}
              scenicAreasWithSpots={scenicAreasWithSpots}
              scenicAreasLoading={scenicAreasLoading}
              otherScenicAreas={otherScenicAreas}
              otherScenicLoading={otherScenicLoading}
              onMasonryItemPress={handleMasonryItemPress}
              onHorizontalItemPress={handleHorizontalItemPress}
              onFoodItemPress={handleFoodItemPress}
              onFoodMorePress={handleFoodMorePress}
              onCurrentScenicPress={handleCurrentScenicPress}
              currentScenicCount={currentScenicAreasCount}
            />
          );

        default:
          return null;
      }
    },
    [
      city,
      weather,
      scenicAreasCount,
      handleLocationPress,
      handleSearchPress,
      handleMapPress,
      currentAttractions,
      foodCulture,
      foodCultureLoading,
      provinceTours,
      provinceToursLoading,
      crossProvinceTours,
      crossProvinceToursLoading,
      scenicAreasWithSpots,
      scenicAreasLoading,
      otherScenicAreas,
      otherScenicLoading,
      handleMasonryItemPress,
      handleHorizontalItemPress,
      handleFoodItemPress,
      handleFoodMorePress,
      handleCurrentScenicPress,
      currentScenicAreasCount,
    ],
  );

  // 获取列表项高度 - 优化性能
  const getItemLayout = useCallback((data, index) => {
    const item = data[index];
    let height = 0;

    switch (item.type) {
      case 'header':
        // 头部高度：状态栏(44) + 城市行(40) + 三栏布局(100) + 搜索框行(60) + padding = 264
        height = 264;
        break;
      case 'content':
        // 内容区域高度：景点区域(400) + 周边景区(200) + 美食(300) + 省内推荐(200) + 跨省路线(200) + 底部空白(100) = 1400
        height = 1400;
        break;
      default:
        height = 100;
    }

    return { length: height, offset: height * index, index };
  }, []);

  // 如果正在初始加载，显示完整的骨架屏
  if (isInitialLoading && city === '定位中...') {
    return (
      <SafeTabBarWrapper>
        <StatusBar barStyle="light-content" backgroundColor="transparent" translucent />
        <FullHomeSkeletonLoader />

        {/* 模态框组件也需要渲染 */}
        <HomeModals
          pickerVisible={pickerVisible}
          cityList={cityList}
          onPickerClose={() => setPickerVisible(false)}
          onCitySelect={handleCitySelect}
        />
      </SafeTabBarWrapper>
    );
  }

  return (
    <SafeTabBarWrapper>
      <StatusBar barStyle="light-content" backgroundColor="transparent" translucent />
      <FlatList
        data={listData}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        getItemLayout={getItemLayout}
        style={styles.container}
        contentContainerStyle={{ paddingBottom: 20 }}
        showsVerticalScrollIndicator={false}
        removeClippedSubviews={true}
        maxToRenderPerBatch={5}
        updateCellsBatchingPeriod={50}
        initialNumToRender={3}
        windowSize={10}
        keyboardShouldPersistTaps="handled"
        scrollEventThrottle={16}
      />

      {/* 模态框组件 */}
      <HomeModals
        pickerVisible={pickerVisible}
        cityList={cityList}
        onPickerClose={() => setPickerVisible(false)}
        onCitySelect={handleCitySelect}
      />

      {/* 自动语音导览 */}
      <AutoVoiceGuide
        visible={showAutoVoiceGuide}
        onClose={async () => {
          clearAutoGuideTimer();
          setShowAutoVoiceGuide(false);
          setShouldAutoStartVoice(false);
          setHasAutoStarted(true);
          try {
            await voiceService.cleanup();
          } catch { }
        }}
        scenicArea={scenicAreasWithSpots[0]}
        currentLocation={currentLocation}
        navigation={navigation}
        autoStart={true}
        autoStartDelay={100}
      />
    </SafeTabBarWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.tertiary,
  },
});
